import constants as con
import pygame
from pygame.locals import *

import postgamebg

class Postgame(object):
    def __init__(self,parent,type):
        self.x = int(con.window_size[0] * 0.05)
        self.y = int(con.window_size[1] * 0.1)
        self.start = (self.x,self.y)

        self.type = type

        self.parent = parent
        self.sprites = pygame.sprite.LayeredUpdates()
        self.font = parent.font

        self.bg = postgamebg.PostgameBG(self)

        # here's hoping we're using fixed width
        (self.width,self.height) = self.font.size('A')
        self.line_length = int( (con.window_size[0] * 0.7) / self.width)

        self.net = parent.income - parent.score - parent.taxes
        self.difficulty = float(parent.bpm) / 10
        self.deathpenalty = self.parent.maxfamily - self.parent.alive
        if (parent.failure + self.deathpenalty) == 0:
            self.bonus = self.difficulty
        else:
            self.bonus = self.difficulty / (parent.failure + self.deathpenalty)
        self.total = int(self.net * self.bonus)

        self.selected = 1
        self.screen = self.screen1
        self.initials = ''

        self.dest = None
        self.error = None
        self.task = 'Open'

    def redraw(self):

        self.sprites.draw(self.parent.screen)
        self.screen()

    def screen1(self):
        pos = self.start

        if self.type == 'lose':
            str = "Your family is dead. You live the rest of your days a hollow shell of a man, with nothing but your life's savings to console you."
        else:
            str = "Retirement! Hopefully you saved enough money to live out the rest of your days in comfort."
            
        pos = self.stringdraw(str,pos)

        pos = self.linedraw("      %10d (income)" % (self.parent.income), pos)
        pos = self.linedraw("    - %10d (spent)" % (self.parent.score), pos)
        pos = self.linedraw("    - %10d (taxes)" % (self.parent.taxes), pos)
        pos = self.linedraw("    ------------", pos)
        pos = self.linedraw("      %10d (retirement fund)" % (self.net), pos)
        pos = (pos[0],pos[1] + self.height * 2)

        pos = self.linedraw("      %10.2f (difficulty rating)" % (self.difficulty), pos)
        pos = self.linedraw("    / %10d (fails)" % (self.parent.failure), pos)
        pos = self.linedraw("    / %10d (deaths)" % (self.deathpenalty), pos)
        pos = self.linedraw("    ------------", pos)
        pos = self.linedraw("      %10.2f (bonus multiplier)" % (self.bonus),pos)

        pos = (pos[0],pos[1] + self.height * 2)

        pos = self.linedraw("      %10d (net)" % (self.net), pos)
        pos = self.linedraw("    * %10.2f (bonus)" % (self.bonus), pos)
        pos = self.linedraw("    ------------",pos) 
        pos = self.linedraw("      %10d (final score)" % (self.total), pos)

        pos = (pos[0],pos[1] + self.height * 2)
        pos = self.linedraw("press enter for next screen",pos)

    def screen2(self):

        pos = self.start

        pos = self.stringdraw("Your final score was %d." % (self.total), pos)
        pos = self.stringdraw("Enter your initials for the leaderboard:", pos)

        buf = self.initials + "_" * (16 - len(self.initials))

        pos = self.stringdraw(buf,pos)

        pos = self.linedraw("press enter to submit",pos)

    def screen3(self):

        pos = self.start

        pos = self.stringdraw("Submitting to server..", pos)

        if self.task == 'Open':
            try:
                import httplib
                self.dest = httplib.HTTPConnection('xzzy.org')
                self.task = 'Submit'
            except:
                self.error = "Can't make HTTP connection."
                self.task = 'Error'

        elif self.task == 'Submit':
            try:
                self.dest.request("GET", self.url)
                self.task = 'ResponseCheck'
            except:
                self.error = "GET call failed."
                self.task = 'Error'

        elif self.task == 'ResponseCheck':

            result = self.dest.getresponse()

            if not result.reason == 'OK':
                self.error = "Failure submitting data: %s %s" % (result.status,result.reason)
                self.task = 'Error'
            else:
                self.task = 'Success'

        elif self.task == 'Error':
            str = "Error detected: %s. Press enter to continue." % (self.error)
            pos = self.stringdraw(str,pos)
        elif self.task == 'Success':
            str = "Submit successful. Press enter to return to main screen."
            pos = self.stringdraw(str,pos)

    def screen4(self):

        pos = self.start
        pos = self.stringdraw("success/failure goes here",pos)

        pos = self.linedraw("press enter to return to main screen",pos)

    def linedraw(self,str,pos):
        x = pos[0]
        y = pos[1]

        label = self.font.render(str, True, con.bgcolor)
        self.parent.screen.blit(label, pos)
        y += self.height

        return (x,y)

    def stringdraw(self,str,pos):

        x = pos[0]
        y = pos[1]

        buf = ''
        for word in str.split():
            # render if adding this word would put us over the limit
            if (len(buf) + len(word)) >= self.line_length:
                label = self.font.render(buf, True, con.bgcolor)
                self.parent.screen.blit(label, (x,y))
                y += self.height
                buf = word
            elif len(buf) == 0:
                buf = word
            else:
                buf = buf + ' ' + word

        if len(buf):
            label = self.font.render(buf, True, con.bgcolor)
            self.parent.screen.blit(label, (x,y))

        y += self.height * 2
        return (x,y)

    def inputDown(self,key):
        letter = None

        if key == K_RETURN:
            self.url = "http://xzzy.org/taxtris/submit.php?id=%s&income=%d&spent=%d&taxes=%d&bpm=%d&failures=%d&score=%d&deaths=%d" % (self.initials,self.parent.income,self.parent.score,self.parent.taxes,self.parent.bpm,self.parent.failure,self.total,self.deathpenalty)
            self.next_screen()
        elif key == K_BACKSPACE or key == K_DELETE:
            if len(self.initials) > 0:
                self.initials = self.initials[0:len(self.initials) - 1]

        elif key > 96 and key < 123:
            letter = chr(key)
        elif key > 47 and key < 58:
            letter = chr(key)

        if not letter is None and self.selected == 2:
            if len(self.initials) < 16:
                self.initials = self.initials + letter
                #print "user input '",letter,"', initials are",self.initials


    def next_screen(self):
        if self.selected == 1:
            self.selected += 1
            self.screen = self.screen2
        elif self.selected == 2:
            self.selected += 1
            self.screen = self.screen3
        elif self.selected == 3:
            self.parent.state = 'Menu'

